<template>
  <div class="camera-container">
    <a-row>
      <a-col :span="18">
        <a-button class="bt-mr8" size="small" @click="moveToCameraAVG">点击自拍一张头像</a-button>
        <a-button class="bt-mr8" type="primary" size="small" @click="captureAvg">拍照</a-button>
        <a-button class="bt-mr8" type="primary" size="small" @click="closeCamera('confirm')">确认</a-button>
      </a-col>
      <a-col :span="6" :push="4">
        <a-button size="small" @click="closeCamera('close')">关闭</a-button>
      </a-col>
    </a-row>
    <div style="height: 10px;"></div>
    <a-row>
      <a-col :span="8">
        <video
          id="video"
          class="pic_video"
          playsinline
          autoplay
          x5-video-player-type="h5"
          style="object-fit:fill"></video>
        <canvas
          v-show="isCanvas"
          id="canvas"
          class="canvas_pic"
          style="margin: 0;padding: 0;"></canvas>
      </a-col>
      <a-col :span="16">
        <ul class="img-wrapper">
          <li v-for="(item, index) in listImg" :key="index">
            <img :src="imgMainUrl + item" alt="" />
            <a-icon type="delete" @click="deleteImg(index)"/>
          </li>
        </ul>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { uploadImg } from '@/api/process'
import {doMainUrl, imgMainUrl} from '@/config/leave.config'

export default {
  name: 'Camera',
  props: {
    isCamera: {
      type: Boolean,
      default: false
    },
    listImgAll: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      imgMainUrl,
      localMediaStream: '',
      imgInfo: '',
      listImg: [],
      isCanvas: false
    }
  },
  created () {
    this.listImg = this.listImgAll.concat()
  },
  methods: {
    moveToCameraAVG () {
      const self = this
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          const getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser, 请换一个浏览器试试！'))
          }
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      if (window.stream) {
        window.stream.getTracks().forEach(track => {
          track.stop()
        })
      }
      const constraints = window.constraints = {
        audio: false,
        video: {
          sourceId: 'default',
          facingMode: {
            exact: 'user'
          }
        }
      }
      navigator.mediaDevices.getUserMedia(constraints)
        .then(function (stream) {
          const video = document.getElementById('video')
          try {
            window.stream = stream
            video.srcObject = stream
          } catch (error) {
            video.src = window.URL.createObjectURL(stream)
          }
          self.localMediaStream = stream
          video.play()
        })
        .catch(function (err) {
          alert(err.name + ': ' + err.message)
        })
    },
    // 停止摄像机
    stopCapture () {
      const video = document.getElementById('video')
      if (!video.srcObject) return
      const stream = video.srcObject
      const tracks = stream.getTracks()
      tracks.forEach(track => {
        track.stop()
      })
    },
    // 头像照片
    captureAvg () {
      const video = document.getElementById('video')
      const canvas = document.getElementById('canvas')
      const ctx = canvas.getContext('2d')
      const CHeight = video.clientHeight // 获取屏幕大小让canvas自适应
      const CWidth = video.clientWidth
      canvas.width = CWidth
      canvas.height = CHeight
      if (this.localMediaStream) {
        ctx.drawImage(video, 0, 0, CWidth, CHeight)
        const dataURL = canvas.toDataURL('image/png') // dataURL = ''
        const file = this.dataURLtoFile(dataURL, this.random())
        console.log('fileName', file)
        const formData = new FormData();
        formData.append('file', file)
        formData.append('biz', 'temp')
        uploadImg(formData).then(data => {
          if (data.code === 0) {
            const filePath = data.message
            if (this.listImg.length >= 3) {
              this.$message.info('图片最多3张')
            } else {
              this.listImg.push(filePath)
              document.getElementById('img').src = doMainUrl + filePath
            }
          } else {
            this.$message.error(data.message)
          }
        }).catch(error => {
          console.log(error);
        })
        // 停止摄像机
        // video.pause()
       // this.stopCapture()
      }
    },
    random () {
      const modeUrl = 'qwertyuiopasdfghjklzxcvbnm'
      console.log(modeUrl[parseInt(Math.random() * 26)], parseInt(Math.random() * 26))
      const fileName = 'avtart_' + modeUrl[parseInt(Math.random() * 26)] + modeUrl[parseInt(Math.random() * 26)] + modeUrl[parseInt(Math.random() * 26)] + modeUrl[parseInt(Math.random() * 26)]
      return fileName
    },
    dataURLtoFile (dataurl, filename) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
      return new File([u8arr], filename, {type:mime});
    },
    deleteImg (index) {
      this.listImg.splice(index, 1)
    },
    closeCamera (type) {
      this.$emit('update:isCamera', false)
      document.getElementById('video').pause()
      this.stopCapture()
      if (type === 'confirm') {
        this.$emit('update:listImgAll', this.listImg)
      }
    }
  }
}
</script>

<style scoped lang="less">
.i-blue {
  color: #389FFD
}
.bt-mr8 {
  margin-right: 8px;
}
.camera-container {
  z-index: 10;
  padding: 20px;
  width: 80%;
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;
  box-shadow: 0px 0px 5px #333333;
  border-radius: 8px;
}
.pic_video, .canvas_pic {
  height: 200px;
  width: 200px;
  border-radius: 10px;
  background-color: #666;
}
.img-wrapper {
  list-style:none;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  li {
    position: relative;
    width: 108px;
    height: 108px;
    margin-right: 8px;
    margin-bottom: 8px;
    img {
      width: 108px;
      height: 108px;
    }
    i {
      position: absolute;
      right: 5px;
      top: 5px;
    }
  }
}
</style>
